package leetcode.code1547;

import java.util.Arrays;
import leetcode.IDebug;
import leetcode.helper.H;

public class Solution2 implements IDebug {

	int[] cuts;
	Integer[][] dp;

	public int minCost(int n, int[] cuts) {
		Arrays.sort(cuts);
		this.cuts = cuts;
		int len = cuts.length;
		dp = new Integer[len][len];
		return f(0, len - 1, 0, n);
	}

	private int f(int l, int r, int left, int right) {
		if (l > r)
			return 0;
		if (dp[l][r] != null) {
			return dp[l][r];
		}
		int L = cuts[l] == left ? l + 1 : l;
		int R = cuts[r] == right ? r - 1 : r;
		if (L > R) {
			return 0;
		}
		if (L == R) {
			dp[l][r] = right - left;
			return right - left;
		}
		int ans = Integer.MAX_VALUE;
		for (int i = L; i <= R; i++) {
			ans = Math.min(ans, f(l, i, left, cuts[i]) + f(i + 1, r, cuts[i], right));
		}
		ans += right - left;
		dp[l][r] = ans;
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(16, this.minCost(7, H.str2array3("[1,3,4,5]")));
		H.compare(22, this.minCost(9, H.str2array3("[5,6,1,4,2]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
